package com.power.test.model.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.power.test.model.IEnum;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * 枚举反序列化器
 */
public class EnumDeserializer<T extends IEnum> extends JsonDeserializer<T> implements ContextualDeserializer {
	/**
	 * 存放枚举类型
	 */
	private Class<T> targetClass = null;

	/**
	 * 构造函数
	 */
	public EnumDeserializer() {
	}

	/**
	 * 枚举类型
	 *
	 * @param targetClass
	 */
	public EnumDeserializer(Class<T> targetClass) {
		this.targetClass = targetClass;
	}

	/**
	 * 枚举类型 反序列化
	 *
	 * @param p
	 * @param ctxt
	 * @return
	 */
	@Override
	public T deserialize(JsonParser p, DeserializationContext ctxt) {
		try {
			String value = p.getText();
			if (StringUtils.isBlank(value)) return null;
			for (T enumObj : targetClass.getEnumConstants()) {
				if (value.equals(enumObj.getValue().toString())) {
					return enumObj;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取枚举类型
	 *
	 * @param ctxt
	 * @param property
	 * @return
	 */
	@Override
	public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
		Class<T> targetClass = (Class<T>) ctxt.getContextualType().getRawClass();
		return new EnumDeserializer(targetClass);
	}
}
